package org.hrqing.chess.frame.listener;

import lombok.extern.slf4j.Slf4j;
import org.hrqing.chess.Launcher;
import org.hrqing.chess.config.props.SystemConfigProps;
import org.hrqing.chess.entity.Log;
import org.hrqing.chess.frame.CenterBackgroundPanel;
import org.hrqing.chess.frame.MainFrame;
import org.hrqing.chess.service.GameService;
import org.hrqing.chess.service.LogService;
import org.hrqing.chess.service.PikaFishService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Hrqing
 */
@Slf4j
public class ContinueMenuItemActionListener implements ActionListener {

    private final MainFrame frame;
    private final CenterBackgroundPanel panel;
    private final SystemConfigProps systemConfigProps;
    private final LogService logService;
    private final GameService gameService;
    private final PikaFishService pikaFishService;

    private DefaultTableModel model;

    public ContinueMenuItemActionListener(MainFrame frame, CenterBackgroundPanel panel, SystemConfigProps systemConfigProps, LogService logService, GameService gameService, PikaFishService pikaFishService) {
        this.frame = frame;
        this.panel = panel;
        this.systemConfigProps = systemConfigProps;
        this.logService = logService;
        this.gameService = gameService;
        this.pikaFishService = pikaFishService;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        List<Log> allLog = logService.findAllLog();

        String[] columns = new String[]{"名称", "难度", "时间", "操作"};
        Object[][] data = new Object[allLog.size()][columns.length];
        for (int i = 0; i < allLog.size(); i++) {
            Log log = allLog.get(i);
            data[i][0] = log.getName();
            data[i][1] = log.getDepth() == null ? null : log.getDepth().getSimple();
            data[i][2] = log.getCreatedTime() == null ? null : log.getCreatedTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            data[i][3] = new String[]{"选择", "删除"};
        }

        model = new DefaultTableModel(data, columns){
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == -1;
            }
        };

        JTable table = new JTable(model);
//        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setRowSelectionAllowed(false);
        table.setColumnSelectionAllowed(false);
        table.setCellSelectionEnabled(false);

        table.setSelectionModel(new DefaultListSelectionModel() {
            @Override
            public void setSelectionInterval(int index0, int index1) {
                super.setSelectionInterval(-1,  -1);
            }
        });
        table.setFocusable(false);
        table.setRowHeight(30);

        table.getColumnModel().getColumn(0).setPreferredWidth(210);
        table.getColumnModel().getColumn(1).setPreferredWidth(40);
        table.getColumnModel().getColumn(2).setPreferredWidth(125);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);

        table.getColumnModel().getColumn(3).setCellRenderer(new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                String[] values = (String[]) value;

                JPanel panel = new JPanel();
                panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 2));
                for (String s : values) {
                    JButton btn = new JButton(s);
                    btn.setMargin(new Insets(2, 5, 2, 5));
                    panel.add(btn);
                }
                return panel;
            }
        });

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Point clickPoint = e.getPoint();
                int col = table.columnAtPoint(clickPoint);
                if (col == 3) {
                    int row = table.rowAtPoint(clickPoint);
                    Rectangle cellRect = table.getCellRect(row,  col, false);
                    Point relativePoint = new Point(
                            clickPoint.x - cellRect.x,
                            clickPoint.y - cellRect.y
                    );

                    // 获取渲染组件并检测按钮点击
                    Component comp = table.prepareRenderer(
                            table.getCellRenderer(row,  col), row, col
                    );
                    comp.setBounds(cellRect);
                    comp.doLayout();

                    detectButtonClick(comp, relativePoint, row, allLog.get(row).getId());
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(475, 300));

        JOptionPane.showOptionDialog(
                frame,
                scrollPane,
                "游戏选择",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.PLAIN_MESSAGE,
                null,
                new Object[]{"关闭"},
                "关闭"
        );

    }

    private void detectButtonClick(Component comp, Point p, int row, String id) {
        if (comp instanceof Container) {
            for (Component child : ((Container)comp).getComponents()) {
                if (child instanceof JButton && contains(child, p))  {
                    // 触发按钮动画
                    animateButtonPress((JButton)child);
                    // 执行业务逻辑
                    handleButtonAction((JButton)child, row, id);
                }
            }
        }
    }

    private boolean contains(Component comp, Point p) {
        Rectangle bounds = comp.getBounds();
        double xs = bounds.getX();
        double xe = bounds.getX() + bounds.getWidth();
        double ys = bounds.getY();
        double ye = bounds.getY() + bounds.getHeight();
        return p.getX() >= xs && p.getX() <= xe && p.getY() >= ys && p.getY() <= ye;
    }

    private void handleButtonAction(JButton child, int row, String id) {
        String gameId = this.panel.getGameId();
        if (child.getText().equals("选择")) {
            if (gameId != null && gameId.equals(id)) {
                JOptionPane.showMessageDialog(frame,  "已经选择当前记录");
                return;
            }
            logService.updateCreatedTime(id, LocalDateTime.now());
            frame.dispose();
            SwingUtilities.invokeLater(()  -> {
                Launcher.frame = new MainFrame(systemConfigProps, logService, gameService, pikaFishService);
                Launcher.frame.afterPropertiesSet();
                Launcher.frame.setVisible(true);
            });
        }else if (child.getText().equals("删除")){
            if (gameId != null && gameId.equals(id)) {
                JOptionPane.showMessageDialog(frame,  "无法删除当前记录");
                return;
            }
            int dialog = JOptionPane.showConfirmDialog(frame, "确定删除", "提示", JOptionPane.OK_CANCEL_OPTION);
            if (dialog == JOptionPane.OK_OPTION) {
                logService.deleteLog(id);
                model.removeRow(row);
            }
        }
    }

    private void animateButtonPress(JButton btn) {
        Timer pressTimer = new Timer(100, ae -> {
            btn.setContentAreaFilled(false);
            btn.setBorderPainted(false);
        });
        pressTimer.setRepeats(false);
        pressTimer.start();

        Timer releaseTimer = new Timer(150, ae -> {
            btn.setContentAreaFilled(true);
            btn.setBorderPainted(true);
        });
        releaseTimer.setRepeats(false);
        releaseTimer.start();
    }

}
